package com.example.csmall.product.repository.impl;

import com.example.csmall.product.pojo.vo.BrandListItemVO;
import com.example.csmall.product.repository.BrandCacheRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Repository
@Slf4j
public class BrandCacheRepositoryImpl implements BrandCacheRepository {

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void save(List<BrandListItemVO> brandList) {
        String key = "brandList";
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        for (BrandListItemVO brandListItemVO : brandList) {
            ops.rightPush(key,brandListItemVO);
        }
        log.debug("已经将mapper层中查询到的brandlist数据存放进redis当中");
    }

    @Override
    public Boolean delete() {
        String key = "brandList";
        Boolean delete = redisTemplate.delete(key);
        log.debug("执行删除redis中brandList数据方法");
        return delete;
    }

    @Override
    public List<BrandListItemVO> list() {
        String key = "brandList";
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        List<Serializable> list = ops.range(key, 0, -1);
        List<BrandListItemVO> brandList = new ArrayList<>();
        for (Serializable serializable : list) {
            brandList.add((BrandListItemVO) serializable);
        }
        log.debug("获取当前redis中brandList中的数据并返回");
        return brandList;
    }


}
